<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片式图区域 -->
    <el-card>
      <!-- 添加分类按键区域 -->
      <el-row>
        <el-col :span="4">
          <el-button type="primary" @click="selectCateDialog">添加分类</el-button>
        </el-col>
      </el-row>

      <!-- 权限列表展示区域 -->
      <tree-table class="tree-table"
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
        stripe
        :show-row-hover="false"
      >
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success" v-if="scope.row.cat_deleted === false" style="color: lightgreen;"></i>
          <i class="el-icon-error" v-if="scope.row.cat_deleted=== true" style="color: lightcoral;"></i>
        </template>
        <template slot="grade" slot-scope="scope">
          <el-tag type="success" v-if="scope.row.cat_level === 0 ">一级</el-tag>
          <el-tag type="warning" v-if="scope.row.cat_level === 1 ">二级</el-tag>
          <el-tag type="danger" v-if="scope.row.cat_level === 2 ">三级</el-tag>
        </template>
        <template slot="operate" slot-scope="scope">
        <el-button type="primary" size="mini" @click="editCateForm(scope.row.cat_id)"><i class="el-icon-edit"></i>编辑</el-button>
        <el-button type="danger" size="mini" @click="removeCateById(scope.row.cat_id)"><i class="el-icon-delete"></i>删除</el-button>
        </template>
      </tree-table>
      <!--      添加分类的对话框-->
      <el-dialog title="添加分类" :visible.sync="addCateDialogVisible" width="50%" @close="addCateDialogClosed">
        <el-form :model="addForm" :rules="editFormRules" ref="addFormRef" label-width="70px">
          <el-form-item label="分类名" prop="cat_name">
            <el-input v-model="addForm.cat_name" ></el-input>
          </el-form-item>
          <el-form-item label="分类父级" >
            <!--:options数据源-->
            <!--:props配置对象-->
                <el-cascader
                  expand-trigger = "hover"
                  v-model="selectedKey"
                  :options="parentCateList"
                  :props="cascaderProps"
                  @change="parentCateChange"
                :clearable="true"
                change-on-select
                  props.expandTrigger="hover"></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="AddCateDialog">确 定</el-button>
        </span>
      </el-dialog>
<!--      修改分类的对话框-->
      <el-dialog title="修改分类" :visible.sync="changeCateDialogVisible" width="50%" @close="editCateDialogClosed">
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
          <el-form-item label="分类名" prop="cat_name" >
            <el-input v-model="editForm.cat_name" ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="changeCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveCateInfo">确 定</el-button>
        </span>
      </el-dialog>
<!--      分页显示区域-->
      <div class="block" >
        <span class="demonstration">完整功能</span>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      //  商品分类列表数据绑定
      cateList: [],
      //  总的数据条数
      total: 0,
      //  是否展示修改分类的对话框
      changeCateDialogVisible: false,
      addCateDialogVisible: false,
      //  绑定编辑对话框的数据
      editForm: {},
      //  绑定添加对话框的数据
      addForm: {
        cat_name: '',
        cat_id: 0,
        cat_level: 0
      },
      //  选中的父级数组
      selectedKey: [],
      //  获取到的父级的数据数组
      parentCateList: [],
      //  指定级联选择器的配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 获取商品分类列表的参数对象
      queryInfo: {
        type: 3,
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 5
      },
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isok'
        },
        {
          label: '排序',
          type: 'template',
          template: 'grade'
        },
        {
          label: '操作',
          type: 'template',
          template: 'operate'
        }
      ],
      // 添加表单的验证规则对象
      editFormRules: {
        cat_name: [
          {
            required: true,
            message: '请输入分类名',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 10,
            message: '用户名的长度在2~10个字符之间',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.getCateLIst()
  },
  methods: {
    async getCateLIst () {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('请求分类列表失败!')
      }
      console.log(res.data.result)
      this.cateList = res.data.result
      this.total = res.data.total
    },
    //  根据id删除分类
    async removeCateById (id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const { data: res } = await this.$http.delete('categories/' + id)

      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败！')
      }

      this.$message.success('删除用户成功！')
      // = res.data
      this.getCateLIst()
    },
    //  监听pagesizes改变的事件
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateLIst()
    },
    //  监听页码值改变的事件
    handleCurrentChange (newPage) {
      console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getCateLIst()
    },
    //  添加分类操作
    async  AddCateDialog() {
      const { data: res } = await this.$http.post('categories', { cat_name: this.addForm.cat_name, cat_pid: this.addForm.cat_pid, cat_level: this.addForm.cat_level })
      if (res.meta.status !== 200) {
        return this.$message.error('添加分类失败！')
      }
      console.log(res.data)
      this.$message.success('添加分类成功！')
    },
    // 获取前两级分类操作
    async  selectCateDialog() {
      this.addCateDialogVisible = true
      const { data: res } = await this.$http.get('categories', { params: { type: 2 } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类失败！')
      }
      console.log(res.data)
      this.parentCateList = res.data
      this.$message.success('获取父级分类成功！')
    },
    //  当选择父级变化时
    parentCateChange () {
      console.log(this.selectedKey)
      //  如果selectKey的长度大于0，说明选中了父级
      if (this.selectedKey.length > 0) {
        this.addForm.cat_pid = this.selectedKey[this.selectedKey.length - 1]
        this.addForm.cat_level = this.selectedKey.length
      } else {
        this.addForm.cat_pid = 0
        this.addForm.cat_level = 0
      }
    },
    //  关闭分类对话框
    addCateDialogClosed () {
      this.addCateDialogVisible = false
      this.$refs.addFormRef.resetFields()
    },
    //  修改分类操作
    async editCateForm (id) {
      this.id = id
      this.changeCateDiologVisible = true
      const { data: res } = await this.$http.get('categories/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类失败！')
      }
      this.editForm = res.data
      console.log(res.data)
    },
    //  保存修改后的分类对话框
    async saveCateInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 发起修改用户信息的数据请求
        const { data: res } = await this.$http.put('categories/' + this.editForm.cat_id, { cat_name: this.editForm.cat_name })
        if (res.meta.status !== 200) {
          return this.$message.error('修改分类失败！')
        }
        console.log(res.data)
        this.getCateLIst()
        this.$message.success('修改分类成功！')
        this.changeCateDiologVisible = false
      })
    },
    //  关闭修改对话框
    editCateDialogClosed () {
      this.changeCateDiologVisible = false
      this.$refs.editFormRef.resetFields()
    }
  }

}
</script>

<style lang="less" scoped>
  .tree-table{
    margin-top: 15px;
  }
  .el-cascader{
    width: 100%;
  }
</style>
